package com.xingchen.loveparttimejob.uitls;


import com.xingchen.loveparttimejob.controller.MyCustomRuntimeException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Encoders;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;

/**
 * @author 小志
 * @date 2024/11/21 - 16:19
 */
public  class JWTUtils {
    //密钥
    private static SecretKey secretKey = new SecretKeySpec("aTYvelYrcXplck9oelZDb0NlZnd6MUZYRTRjR1orbjJYNVBaaHh4bXgzMD0=".getBytes(), "HmacSHA256");
    //生成的jwt
    private static String jwt;

    public JWTUtils() {
    }

    /**
     * 获取密钥对象
     * @return SecretKey对象
     */
    public SecretKey getSecretKey() {
        return secretKey;
    }

    /**
     * 获取密钥字符串
     * @return 密钥字符串
     */
    public String getSecretKeyString(){
        return Encoders.BASE64.encode(secretKey.getEncoded());
    }
    public String getJwt() {
        return jwt;
    }

    /**
     * 生成Token
     * @param id 用户唯一标识
     * @param role 用户角色
     */
    public static JWTUtils generateToken(String id, String role){
        Date date = new Date(new Date().getTime()+3600000);
        jwt = Jwts.builder().claims(createMap(id,role)).signWith(secretKey).expiration(date).compact();
        return new JWTUtils();
    }

    /**
     * 生成Token 可以自定义时间
     * @param id 用户唯一标识
     * @param role 用户角色
     * @param date 设置过期时间
     */
    public static JWTUtils generateToken(String id, String role, Date date){
        jwt = Jwts.builder().claims(createMap(id,role)).signWith(secretKey).expiration(date).compact();
        return new JWTUtils();
    }

    private static HashMap<String,String> createMap(String id,String role){
        HashMap<String, String> map = new HashMap<>();
        map.put("userId",id);
        map.put("role",role);
        return  map;
    }

    /**
     * 获取jwt里面的用户id
     * @return 用户id
     */
    public String getUserId () throws MyCustomRuntimeException {
        if(parseToken(jwt) != null){
           return (String) parseToken(jwt).get("userId");
        }else{
            return null;
        }
    }

    /**
     * 获取角色
     * @return 用户id
     */
    public String getRole () throws MyCustomRuntimeException{
        return (String) Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(jwt).getPayload().get("role");
    }

    /**
     * 生成jwtObject
     * @param jwtString JWT字符串
     * @return JWTUtils对象
     */
    public static JWTUtils generateJwtUtilsObject(String jwtString) {
        jwt = jwtString;
        return new JWTUtils();
    }

    public Claims parseToken(String jwt) throws MyCustomRuntimeException{
        try {
            return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(jwt).getPayload();
        } catch (ExpiredJwtException e) {
            // Token已过期
            throw new MyCustomRuntimeException("用户验证已过期");
        } catch (UnsupportedJwtException e) {
            // 不支持的Token
            throw new MyCustomRuntimeException("用户验证有误");
        } catch (MalformedJwtException e) {
            // Token格式错误
            throw new MyCustomRuntimeException("用户令牌格式错误");
        } catch (SignatureException e) {
            // 签名错误
            throw new MyCustomRuntimeException("用户令牌错误");
        } catch (IllegalArgumentException e) {
            // Token为空
            throw new MyCustomRuntimeException("没有用户令牌");
        }
    }
}
